package com.controller;

import com.model.FlightModel;
import com.services.IFlightServices;
import com.services.impl.FlightServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Program: exam
 * @ClassName: FlightListServletController
 * @Description: 获取航班列表
 * @Author: li
 */
@WebServlet("/flights")
public class FlightListServletController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取查询参数
            String departureCity = request.getParameter("departureCity");
            String arrivalCity = request.getParameter("arrivalCity");
            String departureDate = request.getParameter("departureDate");

            IFlightServices flightServices = new FlightServicesImpl();
            List<FlightModel> flights;

            // 根据参数决定调用哪个查询方法
            if (departureCity != null && arrivalCity != null && departureDate != null) {
                // 带条件的查询
                flights = flightServices.searchFlights(departureCity, arrivalCity, departureDate);
            } else {
                // 查询所有航班
                flights = flightServices.getAllFlights();
            }
            
            result.put("code", 0);
            result.put("msg", "success");
            result.put("data", flights);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "获取航班列表失败：" + e.getMessage());
        }
        
        response.getWriter().write(JSONObject.fromObject(result).toString());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
} 